﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using WinnerCMS.Common;
using EntityFramework.Extensions;
using WinnerCMS.Model;
namespace WinnerCMS.Data
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class UserDal
    {
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        public void Add(User model)
        {
            using (Entities db = new Entities())
            {
                db.Users.Add(model);
                db.SaveChangesAsync().Wait();

            }
        }
        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="model"></param>
        public void Edit(User model)
        {
            using (Entities db = new Entities())
            {
                db.Users.Attach(model);
                db.Entry(model).State = EntityState.Modified;
                db.SaveChangesAsync().Wait();

            }
        }
        /// <summary>
        /// 获取单条数据
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public User GetInfo(int userId)
        {
            using (Entities db = new Entities())
            {
                var query = db.Users.FirstOrDefault(x => x.Id == userId);
                return query;
            }
        }
        /// <summary>
        /// 获取单条数据
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public User GetInfo(string userName)
        {
            using (Entities db = new Entities())
            {
                var query = db.Users.FirstOrDefault(x => x.UserName == userName);
                return query;
            }
        }

        /// <summary>
        /// 获取单条数据，包括扩展属性
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="hasRights"></param>
        /// <returns></returns>
        public User GetInfo(string userName, bool hasRights)
        {
            using (Entities db = new Entities())
            {
                db.Configuration.LazyLoadingEnabled = false;
                var query = db.Users.Include(x => x.Rights).FirstOrDefault(x => x.UserName == userName);
                return query;
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId"></param>
        public void Delete(int userId)
        {
            using (Entities db = new Entities())
            {
                db.Users.Where(x => x.Id == userId).Delete();
                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="newPSW">新密码</param>
        public void ChangPSW(string userName, string newPSW)
        {
            using (Entities db = new Entities())
            {
                var query = db.Users.FirstOrDefault(x => x.UserName == userName);
                if (query != null)
                {
                    query.PassWord = newPSW;

                    db.SaveChangesAsync().Wait();
                }
            }
        }
        /// <summary>
        /// 打开管理员中心的时候绑定数据
        /// </summary>
        /// <returns></returns>
        public IList<User> BindList(bool isAdmin, PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                var query = (from x in db.Users
                             where x.IsAdmin == isAdmin
                             select x);

                pp.RecordCount = query.Count();

                query = query.OrderByDescending(x => x.Id).Skip(pp.Skip).Take(pp.PageSize);

                return query.ToList();
            }
        }

        #region 给会员管理界面绑定分页数据

        /// <summary>
        /// 给会员管理界面绑定分页数据
        /// </summary>
        /// <param name="isAdmin">是否管理员</param>
        /// <param name="sort">搜索字段</param>
        /// <param name="keyword">关键字</param>
        /// <param name="days">过期</param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<User> BindList(bool? isAdmin, string sort, string keyword, DateTime? days, PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                var query = from x in db.Users select x;

                if (isAdmin != null)
                {
                    query = query.Where(x => x.IsAdmin == isAdmin);
                }
                switch (sort)
                {
                    case "UserName":
                        query = query.Where(x => x.UserName.StartsWith(keyword));
                        break;
                    case "PetName":
                        query = query.Where(x => x.PetName.StartsWith(keyword));
                        break;
                    case "QQ":
                        query = query.Where(x => x.QQ.StartsWith(keyword));
                        break;
                    case "eMail":
                        query = query.Where(x => x.EMail.StartsWith(keyword));
                        break;
                    case "IsLocked":
                        int isLocked = int.Parse(keyword);
                        query = query.Where(x => x.IsLocked == isLocked);
                        break;
                    default:
                        break;
                }

                if (days != null)
                {
                    query = query.Where(x => x.LastLoginTime <= days);
                }

                pp.RecordCount = query.Count();
                query = query.OrderByDescending(x => x.Id).Skip(pp.Skip).Take(pp.PageSize);

                return query.ToList();
            }
        }

        #endregion

        /// <summary>
        /// 登录验证成功，更新登录信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="ip"></param>
        /// <returns></returns>
        public void Logined(int userId, string ip)
        {
            using (Entities db = new Entities())
            {
                User model = db.Users.First(x => x.Id == userId);
                model.LoginTimes += 1;
                model.LastLoginTime = DateTime.Now;
                model.LastLoginIP = ip;

                db.SaveChangesAsync().Wait();
            }
        }

        /// <summary>
        /// 获取该用户最高权限等级
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetMaxRank(int userId)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Users
                        where x.Id == userId
                        select x.Roles.Max(y => y.Rank);
                return q.FirstOrDefault();
            }
        }

        /// <summary>
        /// 取得会员Id
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public int GetUserId(string name)
        {
            using (Entities db = new Entities())
            {
                return db.Users.Where(x => x.UserName == name).Select(x => x.Id).First();
            }
        }


        /// <summary>
        /// 修改密码。
        /// </summary>
        /// <param name="name"></param>
        /// <param name="newPSW"></param>
        public void PasswordModify(string name, string newPSW)
        {
            using (Entities db = new Entities())
            {
                User u = db.Users.First(x => x.UserName == name);
                u.PassWord = newPSW;

                db.SaveChangesAsync().Wait();
            }
        }


        #region 批量操作
        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="Ids"></param>
        /// <param name="which"></param>
        public void BatchToDo(string Ids, string which)
        {
            using (Entities db = new Entities())
            {
                switch (which)
                {
                    case "批量删除":

                        db.Database.ExecuteSqlCommand("delete from CMS_Messages where Sender in (select Name from CMS_Users where Id in (" + Ids + "))");
                        db.Database.ExecuteSqlCommand("delete from CMS_Users where Id in (" + Ids + ")");

                        break;
                    case "封号":
                        db.Database.ExecuteSqlCommand("update CMS_Users set IsLocked=1 where Id in (" + Ids + ")");
                        break;
                    case "激活":
                        db.Database.ExecuteSqlCommand("update CMS_Users set IsLocked=0 where Id in (" + Ids + ")");
                        break;

                }
            }
        }
        #endregion

        #region Ajax搜索会员用户名
        /// <summary>
        /// Ajax搜索会员用户名
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public IList<string> SearchMember(string name)
        {
            using (Entities db = new Entities())
            {
                return db.Users.Where(x => x.UserName.Contains(name)).Select(x => x.UserName).ToList();
            }
        }
        #endregion

        #region 扣除点数
        /// <summary>
        /// 扣除点数
        /// </summary>
        /// <param name="pointNum"></param>
        /// <param name="memberId"></param>
        public void KouDianShu(int pointNum, int memberId)
        {

            using (Entities db = new Entities())
            {
                var q = db.Users.First(x => x.Id == memberId);
                q.Point = q.Point - pointNum;

                db.SaveChangesAsync().Wait();
            }
        }

        #endregion

        #region 加点数
        /// <summary>
        /// 加点数
        /// </summary>
        /// <param name="pointNum"></param>
        /// <param name="memberId"></param>
        public void JiaDianShu(int pointNum, int memberId)
        {
            using (Entities db = new Entities())
            {
                var q = db.Users.First(x => x.Id == memberId);
                q.Point = q.Point + pointNum;

                db.SaveChangesAsync().Wait();
            }
        }

        #endregion

    }
}
